<script setup lang="ts">
import {Chart} from "@vue-chart/echart"

const props = defineProps({
  dataSource: {
    type: Array,
    default: () => []
  },
});
const chartType = ref<Number>(1);
const rank = ref<Array<any>>([]);
const options = ref({
  // 统计表名称
  title: {
    text: '销量排行',
    left: 'center',
    top: 20,
    textStyle: {
      color: '#333',
      fontSize: 14,
      fontWeight: 'bold'
    }
  },
  tooltip: {
    trigger: 'item',
    formatter: (value: string) => {
      return '第' + (value.dataIndex+1) + '名<br/>' + rank.value[value.dataIndex].itemName + '<br/>月销量：' + (rank.value[value.dataIndex].monthSale||'--') + '<br/>总销量：' + (rank.value[value.dataIndex].totalSale||'--');
    }
  },
  xAxis: {
    type: 'category',
    data: [],
  },
  yAxis: {
    type: 'value'
  },
  series: [
    {
      data: [],
      type: 'bar',
      showBackground: true,
    }
  ]
})
const showChart = ref(false);
const calcRankData = () => {
  showChart.value = false;
  if (chartType) {
    // 按照月销量对dataSource进行排序
    rank.value = props.dataSource.sort((a, b) => {
      return Number(b.monthSale) - Number(a.monthSale);
    });
  } else {
    // 按照总销量对dataSource进行排序
    rank.value = props.dataSource.sort((a, b) => {
      return Number(b.totalSale) - Number(a.totalSale);
    });
  }
  const xAxisData = [];
  const seriesData = [];
  for (let i = 0; i < rank.value.length; i++) {
    if (i>=199) // 最多对前200名进行统计
      break;
    xAxisData.push('第' + (i + 1) + '名');
    seriesData.push(chartType.value === 1 ? rank.value[i].monthSale : rank.value[i].totalSale);
  }
  options.value.xAxis.data = xAxisData;
  options.value.series[0].data = seriesData;
  nextTick(() => {
    showChart.value = true;
  })
}
onMounted(() => {
  calcRankData();
})
watch(() => chartType.value, () => {
  calcRankData();
})
watch(() => props.dataSource, () => {
  calcRankData();
}, {deep: true})
</script>

<template>
  <a-row>
    <a-col>
      <a-radio-group size="small" v-model:value="chartType">
        <a-radio-button :value="1">
          月销量(参考值)
        </a-radio-button>
        <a-radio-button :value="2">
          总销量(参考值)
        </a-radio-button>
      </a-radio-group>
    </a-col>
  </a-row>
  <Chart :options="options" style="height: 300px;" v-if="showChart"/>
</template>

<style scoped>
</style>
